package com.sk.bilibili.service;

import com.sk.bilibili.other.R;
import com.sk.bilibili.property.CloudProperty;
import com.sk.bilibili.property.SmsProperty;
import com.sk.bilibili.utils.RedisUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 邵康
 * @date 2021/11/22 16:45
 */
@Service
public class SmsCodeService implements InitializingBean {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SmsProperty smsProperty;
    private Random random;

    public R<Void> sendMsg(String phone) {
        if(redisUtils.contains(phone))return R.error("不要频繁发送短信");
        String code=generateCode();
        int loseTime = smsProperty.getLoseTime();
        redisUtils.set(phone,code, loseTime, TimeUnit.SECONDS);
        return R.res(smsService.sendMsg(phone,code,String.valueOf(loseTime)));
    }

    // 这里验证码必须使用数字
    private String generateCode() {
        StringBuilder builder=new StringBuilder();
        for (int i = 0; i < smsProperty.getCodeLen(); i++) {
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }

    public R<Void> checkCode(String phone, String code) {
        if(!redisUtils.contains(phone))return R.error("验证码已失效");
        return R.res(code.equals(redisUtils.get(phone)));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        random=new Random();
    }

}
